<template>
  <div class="comment-section">
    <h3>评论</h3>
    
    <div class="comment-form" v-if="isLoggedIn">
      <form @submit.prevent="addNewComment">
        <div class="form-group">
          <label for="comment"></label>
          <textarea
            id="comment"
            v-model="newComment"
            required
            placeholder="在此输入评论..."
            rows="3"
          ></textarea>
        </div>
        
        <div class="form-actions">
          <button type="submit" class="btn btn-primary">发送评论</button>
        </div>
      </form>
    </div>
    
    <div class="comment-login-prompt" v-else>
      <p>请 <a class="shubiao" @click="showRegisterModal">注册</a> 或 <a class="shubiao" @click="showLoginModal">登录</a> 后添加评论。</p>
    </div>
    
    <div class="comment-list" v-if="comments && comments.length > 0">
      <div class="comment" v-for="comment in comments" :key="comment.id">
        <div class="comment-header">
          <span class="comment-author">{{ comment.authorName || 'Anonymous' }}</span>
          <span class="comment-date">{{ comment.addedTime }}</span>
        </div>
        <div class="comment-content">
          {{ comment.body }}
        </div>
      </div>
    </div>
    
    <div class="no-comments" v-else>
      <p>暂无评论，赶紧来评论吧!</p>
    </div>
    
  </div><teleport to="body">
    <LoginForm 
      v-if="showLogin" 
      @close="showLogin = false" 
      @login-success="handleLoginSuccess"
      @Login-Reg="LoginReg"
    />
    <RegisterForm 
      v-if="showRegister" 
      @close="showRegister = false" 
      @register-success="handleRegisterSuccess"
      @Reg-login="RegLogin"
    />
  </teleport>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { useUserStore } from '@/stores/user';
import apiService from '@/services/api';
import LoginForm from '@/components/auth/LoginForm.vue';

import { useRoute, useRouter } from 'vue-router';
import RegisterForm from '@/components/auth/RegisterForm.vue';

const props = defineProps({
  movieId: {
    type: [Number, String],
    required: true
  },
  movieTitle: {
    type: String,
    required: true
  }
});

const showLogin = ref(false);
const showRegister = ref(false);
const store = useUserStore();
const isLoggedIn = computed(() => store.isLoggedIn);

const router = useRouter();
const route = useRoute();
const newComment = ref('');
const comments = ref([]);
const isLoading = ref(false);
const handleLoginSuccess = () => {
  showLogin.value = false;
  router.push('/');

};
const RegLogin = () =>{
  showLogin.value = true
  showRegister.value = false
}
const LoginReg = () =>{
  showLogin.value = false
  showRegister.value = true
}
// 处理注册成功逻辑
const handleRegisterSuccess = () => {
  showRegister.value = false;
  showLogin.value = true;
};
// 显示注册模态框
const showRegisterModal = () => {
  showRegister.value = true;
};
const showLoginModal = ()=>{
  showLogin.value = true
}
const fetchComments = async () => {
  if (!props.movieId) return;
  try {
    const response = await apiService.getComments({
      articleid:props.movieId,
      replyType:'电商'
    });
    comments.value = response;
  } catch (error) {
    console.error('Failed to fetch comments:', error);
  }
};

onMounted(fetchComments);

watch(
  () => props.movieId,
  fetchComments
);
const addNewComment = async () => {
  if (!newComment.value.trim()) return;
  
  try {
    await apiService.addComment({
      articleid: route.params.id, // 确保 movieId 正确
      body: newComment.value,
      userid: store.getUserId
    });
    
    // 清空输入框并刷新评论列表
    newComment.value = '';
    await fetchComments();
  } catch (error) {
    console.error('Failed to add comment:', error);
    alert('发送失败请重试');
  }
};

// 格式化日期
const formatDate = (dateString) => {
  const options = { year: 'numeric', month: 'short', day: 'numeric' };
  return new Date(dateString).toLocaleDateString(undefined, options);
};
</script>

<style scoped>
.comment-section {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  margin-top: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.shubiao{
  cursor: pointer;
}
.comment-section h3 {
  margin-top: 0;
  color: #1a1a2e;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.comment-form {
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
}

.form-group textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  resize: vertical;
  min-height: 80px;
}

.comment-login-prompt {
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
  text-align: center;
  color: #666;
}

.comment-login-prompt a {
  color: #e94560;
  text-decoration: none;
  font-weight: 500;
}

.comment-list {
  margin-top: 20px;
}

.comment {
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.comment-author {
  font-weight: 500;
  color: #1a1a2e;
}

.comment-date {
  color: #888;
  font-size: 0.9rem;
}

.comment-content {
  font-size: 0.95rem;
  line-height: 1.4;
}

.no-comments {
  text-align: center;
  padding: 20px;
  color: #888;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-weight: 500;
}

.btn-primary {
  background-color: #e94560;
  color: white;
}

.btn:hover {
  opacity: 0.9;
}
</style>